﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using MediaLibraryManagement.BLL;
using MediaLibraryManagement.Common;
using MediaLibraryManagement.Entity;

namespace MediaLibraryManagement.UI
{
    public partial class AlbumDetails : Form
    {
        private Artist _artist;
        private Album _album;
        private float _rating;
        private int _ratingCount;

        public AlbumDetails()
        {
            InitializeComponent();
            dgvTrackList.AutoGenerateColumns = false;
        }

        public AlbumDetails(Artist artist, Album album)
        {
            InitializeComponent();
            dgvTrackList.AutoGenerateColumns = false;
            _artist = artist;
            _album = album;
        }

        private void AlbumDetails_Load(object sender, EventArgs e)
        {
            if (_artist != null && _album != null)
            {
                txtTitle.Text = _album.Title;
                txtArtist.Text = (_artist.FirstName + " " + _artist.LastName).Trim();
                dtpReleaseDate.Value = _album.ReleaseDate;
                txtGenre.Text = _album.Genre;
                txtDescription.Text = _album.Description;
                _rating = _album.Rate;
                _ratingCount = _album.RatingCount;
                lblRatingNumber.Text = Math.Round(_rating, 2) + "/5";
                dgvTrackList.DataSource = _album.Songs;
                if (GlobalObjects.CurrentUser != null)
                {
                    if (GlobalObjects.CurrentUser.Privilege != Privileges.Viewer)
                    {
                        SetReadOnly(false);
                    }
                    else
                    {
                        SetReadOnly(true);
                    }
                    btnSave.Visible = true;
                }
                else
                {
                    SetReadOnly(true);
                    cboRating.Enabled = false;
                    btnSave.Visible = false;
                }
            }
            else
            {
                if(_artist != null)
                {
                    txtArtist.Text = (_artist.FirstName + " " + _artist.LastName).Trim();
                }
                _rating = 0;
                _ratingCount = 0;
            }
        }

        #region Private Methods

        private void SetReadOnly(bool isReadOnly)
        {
            txtTitle.ReadOnly = isReadOnly;
            dtpReleaseDate.Enabled = !isReadOnly;
            txtGenre.ReadOnly = isReadOnly;
            txtDescription.ReadOnly = isReadOnly;
            dgvTrackList.ReadOnly = isReadOnly;
            btnBrowseImage.Enabled = !isReadOnly;
        }

        #endregion

        private void btnBrowseImage_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlgOpenFile = new OpenFileDialog();
            dlgOpenFile.Filter = GlobalObjects.ImageFilter;
            dlgOpenFile.Multiselect = false;
            if (dlgOpenFile.ShowDialog() == DialogResult.OK)
            {
                Image image = Image.FromFile(dlgOpenFile.FileName);
                Image newImage = Utilities.ScaleImage(image, picAlbumImage.Width, picAlbumImage.Height);
                picAlbumImage.Image = newImage;
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            AlbumBLL business = new AlbumBLL();
            Album album = new Album();
            album.Title = txtTitle.Text;
            album.ArtistID = _artist.ID;
            album.ReleaseDate = dtpReleaseDate.Value;
            album.Genre = txtGenre.Text;
            album.Description = txtDescription.Text;
            album.Image = picAlbumImage.Image;
            List<Song> songs = new List<Song>();
            foreach (DataGridViewRow row in dgvTrackList.Rows)
            {
                if (dgvTrackList.Rows.IndexOf(row) != dgvTrackList.Rows.Count - 1)
                {
                    Song song = new Song();
                    song.Title = row.Cells["TrackList_Title"].Value.ToString().Trim();
                    song.Length = row.Cells["TrackList_Length"].Value.ToString().Trim();
                    song.URL = row.Cells["TrackList_Link"].Value.ToString().Trim();
                    songs.Add(song);
                }
            }
            album.Songs = songs;
            if (cboRating.SelectedIndex > 0)
            {
                int selectedRate = (int)cboRating.SelectedIndex;
                _rating = (float)(_rating * _ratingCount + selectedRate) / (_ratingCount + 1);
                _ratingCount++;
            }
            album.Rate = _rating;
            album.RatingCount = _ratingCount;
            try
            {
                if (_album == null)
                {
                    business.Insert(album);
                    MessageBox.Show("Thêm album mới thành công.");
                    this.Close();
                }
                else
                {
                    album.ID = _album.ID;
                    business.Update(album);
                    MessageBox.Show("Cập nhật album thành công.");
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Lỗi hệ thống:\n" + ex, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}